package com.ciwong.epaper.modules.login;

import android.text.TextUtils;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.LoginInfo;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录数据逻辑层实现
 * Created by lqi on 2017/2/22.
 */
public class LoginModelImpl implements LoginContract.LoginModel {
    @Override
    public void login(final EApplication application, String usernameStr, final String passwordBefor, String uuid, String captchaCode,  final LoginFinishedListener listener, final boolean isMobile) {
        final String passWord = AESCBCUtil.encrypt(passwordBefor, AESCBCUtil.AESCBC_HEX);
        final String userName = AESCBCUtil.encrypt(usernameStr, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().getUserToken(application, userName, passWord, uuid, captchaCode, new BaseCallBack() {
            @Override
            public void success(Object data) {
                LoginInfo loginInfo = (LoginInfo) data;
                if (null != loginInfo.getMobile() && loginInfo.getMobile().length() > 0) {
                    loginInfo.setMobile(AESCBCUtil.decrypt(loginInfo.getMobile(), AESCBCUtil.AESCBC_HEX));
                }
                saveUserSchoolInfo(loginInfo, application, isMobile, passWord);
                //保存token信息到数据库
                LoginToken.saveTokenInfoToContentProividerByPad(application, loginInfo, null);
                saveTokenInfo(loginInfo);
                getMyOneSchool(application, loginInfo, listener, passwordBefor);
                //上报登录信息
                FeedbackUtil.getInstance().asyncUploadUserLogin();
            }

            @Override
            public void failed(int errorCode, Object data) {

                listener.onLoginFiled(errorCode, String.valueOf(data));
            }

            @Override
            public void failed(Object data) {
                listener.onLoginFiled(data);
            }
        });

    }

    /**
     * 获取学校信息
     */
    public void getMyOneSchool(final EApplication application, final LoginInfo loginInfo, final LoginFinishedListener listener, final String passWord) {
        MeDao.getInstance().getSchoolInfo(new BaseCallBack() {
            @Override
            public void failed(Object data) {
                listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passWord);
            }

            @Override
            public void failed(int errorCode, Object data) {
                listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passWord);
            }

            @Override
            public void success(Object data) {
                application.setIsGetSchool(1);
                listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passWord);
                if (null != data) {
                    List<SchoolDetail> schoolDetails = (List<SchoolDetail>) data;
                    if (schoolDetails.size() > 0) {
                        SchoolDetail mSchoolDetail = schoolDetails.get(0);
                        saveUserSchoolInfo(application, loginInfo, mSchoolDetail);
                    }
                }
            }
        });
    }

    /**
     * 保存用户数据到本地
     *
     * @param loginInfo
     * @param application
     * @param isMobile
     * @param password
     */
    private void saveUserSchoolInfo(LoginInfo loginInfo, EApplication application,
                                    boolean isMobile, String password) {
        final UserInfoBase userInfoBase = new UserInfoBase();
        userInfoBase.setUserId(Long.parseLong(loginInfo.getUserId()));
        userInfoBase.setIsMobile(isMobile);
        userInfoBase.setAvatar(loginInfo.getAvatar());
        userInfoBase.setNickName(loginInfo.getNickName());
        userInfoBase.setMobile(loginInfo.getMobile());
        userInfoBase.setRealName(loginInfo.getRealName());
        application.setUserInfoBase(userInfoBase);
        EApplication.MOBILE = loginInfo.getMobile();
        final UserAccountInfo userAccountInfo = new UserAccountInfo();
        userAccountInfo.setPhoneNumber(loginInfo.getMobile());
        userAccountInfo.setPhonelogin(isMobile);
        userAccountInfo.setUserId(Long.parseLong(loginInfo.getUserId()));
        userAccountInfo.setUserPwd(password);
        userAccountInfo.setAvatar(loginInfo.getAvatar());

        try {

            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_INFO_BASE, userInfoBase);
            CWSys.setSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, userInfoBase.getUserId());

            //清除用户学习班级信息
            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_SCHOOL_BASE, null);
            CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL + userInfoBase.getUserId(), null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, null);
            application.setSchoolDetail(null);
            application.setClazz(null);
            application.setClazzs(null);

            CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), userInfoBase.getMobile());


        } catch (IOException e) {
            e.printStackTrace();
        }
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        List<UserAccountInfo> userAccountList;
                        if (data instanceof List) {
                            userAccountList = (ArrayList<UserAccountInfo>) data;
                        } else {
                            userAccountList = new ArrayList<>();
                        }
                        if (EConstants.IS_YOUKE) {
                            //DO NOTHING
                        } else {
                            for (int i = 0; i < userAccountList.size(); i++) {
                                if (userAccountList.get(i).getUserId() == userAccountInfo.getUserId()) {
                                    userAccountList.remove(i);
                                }
                            }
                            //如果是免密码登录，只记住一个用户名
                            if ("100151".equals(EConstants.CLIENT_ID)) {
                                userAccountList.clear();
                            }
                            userAccountList.add(0, userAccountInfo);
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                    (Serializable) userAccountList, false);
                        }


                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                    @Override
                    public void failed(Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                }, false);

    }

    /**
     * 保存用户学校数据到本地
     *
     * @param mSchoolDetail
     * @param application
     */
    private void saveUserSchoolInfo(EApplication application, LoginInfo loginInfo, SchoolDetail mSchoolDetail) {
        try {
            application.setMySchool(mSchoolDetail);
            application.setSchoolDetail(mSchoolDetail);
            if (mSchoolDetail != null) {
                CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_SCHOOL_BASE, mSchoolDetail);
                CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL + loginInfo.getUserId(), mSchoolDetail);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化本地账号信息
     *
     * @param userAccountInfo
     */
    private void createUerLoginList(UserAccountInfo userAccountInfo) {
        if (EConstants.IS_YOUKE) {
            //DO NOTHING
        } else {
            List<UserAccountInfo> userInfoBaseList = new ArrayList<>();
            userInfoBaseList.add(userAccountInfo);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                    (Serializable) userInfoBaseList, false);

            //
        }

    }

    /**
     * 保存用户token
     *
     * @param info
     */
    public void saveTokenInfo(LoginInfo info) {
        BaseRequest.VerifyInfo verifyInfo = new BaseRequest.VerifyInfo();
        verifyInfo.setAccessToken(info.getAccessToken());
        verifyInfo.setClientId(EConstants.CLIENT_ID);
        verifyInfo.setClientIp(DeviceUtils.getLocalIpAddress());
        verifyInfo.setOauthVersion("2.0");
        verifyInfo.setScope("all");
        verifyInfo.setRefreshToken(info.getRefreshToken());
        verifyInfo.setExpiresIn(info.getExpiresIn());
        try {
            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                    verifyInfo);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            HttpRequest.setVerifyInfo(verifyInfo);
        }
    }
}
